package cn.qiba.sms.service.impl;

import cn.hutool.json.JSONUtil;
import cn.qiba.sms.bo.common.SmsResult;
import cn.qiba.sms.bo.aliyun.AliyunSmsBO;
import cn.qiba.sms.kit.AliyunSmsKit;
import cn.qiba.sms.service.ISmsService;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AliyunSmsServiceImpl implements ISmsService<AliyunSmsBO> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AliyunSmsKit aliyunSmsKit;

    @Override
    public SmsResult send(AliyunSmsBO smsBO) {
        try {
            logger.info("阿里云短信调用参数："+JSONUtil.toJsonStr(smsBO));
            SendSmsResponse sendSmsResponse = aliyunSmsKit.sendSms(smsBO.getPhoneNumber(),smsBO.getSignName(),smsBO.getTemplateCode(), JSONUtil.toJsonStr(smsBO.getTemplateParam()==null?"":smsBO.getTemplateParam()),smsBO.getOutId());
            logger.info("阿里云短信调用返回结果："+JSONUtil.toJsonStr(sendSmsResponse));
            if("OK".equals(sendSmsResponse.getCode())){
                return SUCCESS;
            }else{
                return new SmsResult(sendSmsResponse.getCode(),sendSmsResponse.getMessage());
            }
        } catch (ClientException e) {
            logger.error("阿里云短信发送失败",e);
            return new SmsResult(e.getErrCode(),e.getErrMsg());
        }
    }
}
